package hn.sigit.view.converter;

import hn.sigit.logic.general.impl.ResourceBundleHelperImpl;
import hn.sigit.model.hnd.cadastre.HND_Layer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;

public class HND_LayerConverter implements Converter {
	private static ResourceBundleHelperImpl resBundle = new ResourceBundleHelperImpl();
	private static String DEFAULT_OPTION = resBundle.loadMessage("txt.select_item");
	
	private List<HND_Layer> itemList = new ArrayList<HND_Layer>();
	private List<SelectItem> selectItems = new ArrayList<SelectItem>();
	private Map<Long, HND_Layer> layerMap = new HashMap<Long, HND_Layer>();
	
	
	public void setItemList(List<HND_Layer> itemList) {
		this.itemList = new ArrayList<HND_Layer>(itemList);
		this.selectItems = new ArrayList<SelectItem>();
		this.layerMap = new HashMap<Long, HND_Layer>();
		
		selectItems.add(new SelectItem("", DEFAULT_OPTION));
		for (HND_Layer l : this.itemList) {
			selectItems.add(new SelectItem(String.valueOf(l.getIID()), l.getName()));
			layerMap.put(l.getIID(), l);
		}
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		value = value.trim();
		if (value.equals("") || value.equals(DEFAULT_OPTION))
			return null;
		return layerMap.get(Long.parseLong(value));
	}


	@Override
	public String getAsString(FacesContext context, UIComponent component, Object object) {
		if (object == null) return "";
		
		if (object instanceof String) {
			if (((String) object).trim().equals(""))
				return DEFAULT_OPTION;
			else
				return object.toString();
		}
		return String.valueOf( ((HND_Layer) object).getIID() );
	}


	public List<SelectItem> getSelectItems() {
		return Collections.unmodifiableList(selectItems);
	}

}
